package org.jeecg.common.util.valid;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.houbb.data.factory.core.util.DataUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static cn.hutool.core.text.CharSequenceUtil.isBlank;

/**
 * @author zjarlin
 * @since 2023/10/7 14:03
 */
@Data
@RestController
public class UserValidTest {
    @CustomValidator(expression = "@projectService.testspel(@xxbean.getLoginRoleCode())", message = "登录人角色必须满足要求", useSpel = true)
//    @CustomValidator(expression = "#this.isRoleAllow(#this.roleCode,'admin','otherCode')", message = "登录人角色必须满足要求", useSpel = true)
    @ApiModelProperty("角色编码")
    String roleCode;

    @CustomValidator(expression = "checkPhone", message = "手机号必须11位")
    @ApiModelProperty("手机号")
    @NotBlank
    String phone;


    //    @CustomValidator(expression = "checkAge", message = "年龄必须大于3")
    @ApiModelProperty("年龄")
    @NotNull(message = "年龄不能为空")
    @CustomValidator(expression = "#this.age>0", message = "年龄需要满足spel表达式", useSpel = true)
    Integer age;

    @ApiModelProperty("证书")
    @NotBlank
    String 证书;
    @CustomValidator(expression = "checkZs", message = "如果有证书,则必须填证书编号")
    String 证书编号;
    private TeacherTest teacherTest;
    private List<BoyTest> boyTest;

    public static void main(String[] args) {
        UserValidTest userTest = DataUtil.build(UserValidTest.class);
        userTest.setPhone("133038867771");
        userTest.setAge(-1);
//        userTest.setAge(null);
        userTest.setRoleCode("admin");
        userTest.set证书("ddjaosidjoasdj");
        userTest.set证书编号("");
        List<Valids.Des> validDes = Valids.getValidDes(userTest);
        System.out.println(validDes);
    }


    public boolean checkZs() {
        boolean equals = StrUtil.equals(证书, "无");
        if (equals) {
            return true;
        }
        return StrUtil.isNotBlank(证书) && StrUtil.isNotBlank(证书编号);
    }


    /**
     * 测试spel校验
     *
     * @param currentRoleCode
     * @param roleCodes       入参
     * @return boolean
     * @author zjarlin
     * @since 2023/10/09
     */

    public boolean isRoleAllow(String currentRoleCode, String... roleCodes) {
        UserValidTest userTest = this;

        if (ArrayUtil.isEmpty(roleCodes)) {
            return false;
        }
        boolean b = Arrays.stream(roleCodes).anyMatch(e -> StrUtil.contains(e, currentRoleCode));
        return b;
    }


    public boolean checkPhone() {
        if (isBlank(phone)) {
            return true;
        }
        return phone.length() == 11;
    }

    public boolean checkAge() {
        if ((Objects.isNull(age))) {
            return true;
        }
        return age > 3;
    }

}
